package com.jpm.fxcutter
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.utils.getQualifiedClassName;
	import flash.events.IOErrorEvent;
	import com.adobe.images.PNGEncoder;
	import flash.utils.ByteArray;
	import flash.filesystem.FileStream;
	import flash.filesystem.FileMode;
	
	/**
	 * ...
	 * @author Jonboy
	 */
	public class Main extends Sprite
	{
		private var assets:File = File.desktopDirectory.resolvePath("syspics");
		private var counter:int = 1;
		private var frame:int = 1;
		
		public function Main():void
		{
			if (stage)
				init();
			else
				addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			workOn(assets);
		}
		
		private function workOn(directory:File):void
		{
			var dir:Array = directory.getDirectoryListing();
			
			for each (var file:File in dir)
			{
				var loader:Loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ldrDone);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ldrError);
				loader.load(new URLRequest(file.url));
			}
		
		}
		
		private function ldrDone(event:Event):void
		{
			var srcBitmap:Bitmap = event.target.content;
			var dimensions:int = 31;
			
			if (event.target.url.indexOf("DamageFX") != -1) {
				dimensions = 32;
			} else if (event.target.url.indexOf("Spells") != -1) {
				dimensions = 38;
			}
			
			for (var y:int = 0; y < srcBitmap.height; y += dimensions)
			{
				
				counter++;
				frame = 0;
				
				for (var x:int = 0; x < srcBitmap.width; x += dimensions)
				{
					
					frame++;
					
					var dstBitmapData:BitmapData = new BitmapData(dimensions, dimensions, true);
					dstBitmapData.copyPixels(srcBitmap.bitmapData, new Rectangle(x, y, dimensions, dimensions), new Point());
					
					//addChild(new Bitmap(dstBitmapData));
					var byteArray:ByteArray = PNGEncoder.encode(dstBitmapData);
					var fileName:String = event.target.url.replace("syspics", "syspicsout");
					var assetsout:File = new File(fileName.substring(0, fileName.lastIndexOf(".")) + "\\fx" + counter + "_000" + frame + ".png");
					var fs:FileStream = new FileStream();
					
					try
					{
						fs.open(assetsout, FileMode.WRITE);
						fs.writeBytes(byteArray);
						fs.close();
						trace(assetsout.name);
					}
					catch (e:Error)
					{
						trace(e.message);
					}
				}
				
			}
		
		}
		
		private function ldrError(event:Event):void
		{
			trace("Failed to load " + event.target.content);
		}
	}
}